import crypto from 'crypto';

export function hashPassword(password: string): string {
  return crypto.createHash('sha256').update(password).digest('hex');
}

export function verifyPassword(password: string, hash: string): boolean {
  return hashPassword(password) === hash;
}

// Minimal token creation/parsing for demo (do NOT use in production)
const SECRET = process.env.JWT_SECRET || 'dev_secret';

export function sign(payload: any): string {
  const base = Buffer.from(JSON.stringify(payload)).toString('base64');
  const sig = crypto.createHmac('sha256', SECRET).update(base).digest('base64');
  return `${base}.${sig}`;
}

export function verify(token: string): any | null {
  try {
    const [base, sig] = token.split('.');
    const expected = crypto.createHmac('sha256', SECRET).update(base).digest('base64');
    if (expected !== sig) return null;
    return JSON.parse(Buffer.from(base, 'base64').toString());
  } catch {
    return null;
  }
}
